import general.AuctioneerClientInterface;
import general.Bid;
import general.ProductPrice;

import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.RemoteObject;
import java.util.UUID;
import java.util.Vector;

public class EnglishAuctioneer extends Auctioneer {
	private Bid fWinningBid;

	public EnglishAuctioneer() throws IOException {
		super();
		fWinningBid = null;
	}

	protected ProductPrice selectWinner() {
		fWinner = fWinningBid.getBidder();
		fBidders.remove(fWinner);
		return fWinningBid.getProductPrice();
	}

	public void joinAuction(RemoteObject c, String name, UUID pID) throws RemoteException {
		if (fRunning != null && fRunning.isRunning()) {
			if (fReq.getProductID() == pID) {
				notifyJoin(name);
				fBidders.add(c);
			}
		} else {
			throw new RemoteException("No Auction Running");
		}
	}

	public void notifyJoin(String name) {
		for (RemoteObject re : fBidders) {
			if (re != null) {
				try {
					((AuctioneerClientInterface) re).notifyJoin(name);
				} catch (RemoteException e) {
					// Bidder Unreachable
					System.out.println("Notify Join: Bidder unreachable");
				}
			}
		}
	}

	public void placeBid(Bid b) {
		if (fRunning != null && fRunning.isRunning()) {
			if (b.isLarger(fWinningBid)) {
				fWinningBid = b;
			}
		}
	}

	public String getType() {
		return "English Auction";
	}

	protected void cleanUp() {
		fWinningBid = null;
		fRunning = null;
		fReq = null;
	}

	protected void newAuction() {
		fStatus = -1;
		fRunning = null;
		fBidders = new Vector<RemoteObject>();
		fWinner = null;
		fWinningBid = new Bid(fReq.getProductPrice(), null);
	}

	protected void updateBidders() {
		for (RemoteObject re : fBidders) {
			if (re != null) {
				try {
					((AuctioneerClientInterface) re).updateBidders(fWinningBid);
				} catch (RemoteException e) {
					// CLient unreachable
					System.out.println("UpdateBidders: Client Unreachable");
				}
			}
		}
	}
}
